package com.bookpavilion.file.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.PutObjectResult;
import com.bookpavilion.file.config.AliyunOSSConfig;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

@Service
public class FileService {
    private static final String[] FILE_TYPE = new String[]{".bmp",".jpg",".jpeg",
            ".gif",".png",".avi",".mp3",".mov"};

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    @Autowired
    private OSS ossClient;

    public Map<String,Object> upload(MultipartFile file){
        Map<String,Object> resultMap = new HashMap<>();

        boolean isLegal = false;
        for (String type :
                FILE_TYPE) {
            if(StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
                resultMap.put("isLegal",true);
                break;
            }
        }
        if (resultMap==null){
            resultMap.put("isLegal",false);
            return resultMap;
        }
        String filename = file.getOriginalFilename();
        String filePath=  getFilePath(filename);
        String fileURL= "http://"+aliyunOSSConfig.getBucketName()+"."+aliyunOSSConfig.getEndpoint().substring(7)+"/"+filePath;
        try {
            ossClient.putObject(aliyunOSSConfig.getBucketName(), filePath, new ByteArrayInputStream(file.getBytes()));
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("isLegal",false);
        }
        resultMap.put("fileURL",fileURL);
        return resultMap;
    }

    private String getFilePath(String filename) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + dateTime.toString("dd") + "/" + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(filename, ".");
    }


    public boolean delete(String filePath){
        try{
            ossClient.deleteObject(aliyunOSSConfig.getBucketName(), filePath);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
